/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.supplier.modular.structure.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.supplier.core.enums.SupplierBuildInEnum;
import vip.xiaonuo.supplier.core.enums.SupplierDataTypeEnum;
import vip.xiaonuo.supplier.modular.structure.org.entity.SupplierOrg;
import vip.xiaonuo.supplier.modular.structure.org.enums.SupplierOrgCategoryEnum;
import vip.xiaonuo.supplier.modular.structure.org.mapper.SupplierOrgMapper;
import vip.xiaonuo.supplier.modular.structure.org.param.*;
import vip.xiaonuo.supplier.modular.structure.org.service.SupplierOrgService;
import vip.xiaonuo.supplier.modular.structure.position.entity.SupplierPosition;
import vip.xiaonuo.supplier.modular.structure.position.service.SupplierPositionService;
import vip.xiaonuo.supplier.modular.structure.user.entity.SupplierUser;
import vip.xiaonuo.supplier.modular.structure.user.service.SupplierUserService;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.sys.api.SysRoleApi;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 机构Service接口实现类
 *
 * @author xuyuxiang
 * @date 2022/2/23 18:43
 **/
@Service
public class SupplierOrgServiceImpl extends ServiceImpl<SupplierOrgMapper, SupplierOrg> implements SupplierOrgService {

    public static final String ORG_CACHE_ALL_KEY = "sys-org:all";

    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private SysRoleApi sysRoleApi;

    @Resource
    private SupplierPositionService supplierPositionService;

    @Resource
    private SupplierUserService supplierUserService;

    @Override
    public Page<SupplierOrg> page(SupplierOrgPageParam supplierOrgPageParam) {
        QueryWrapper<SupplierOrg> queryWrapper = new QueryWrapper<SupplierOrg>().checkSqlInjection();
        // 查询部分字段
        queryWrapper.lambda().select(SupplierOrg::getId, SupplierOrg::getParentId, SupplierOrg::getName,
                SupplierOrg::getCategory, SupplierOrg::getSortCode);
        if(ObjectUtil.isNotEmpty(supplierOrgPageParam.getParentId())) {
            queryWrapper.lambda().eq(SupplierOrg::getParentId, supplierOrgPageParam.getParentId());
        }
        if(ObjectUtil.isNotEmpty(supplierOrgPageParam.getSearchKey())) {
            queryWrapper.lambda().like(SupplierOrg::getName, supplierOrgPageParam.getSearchKey());
        }
        //数据归属
        queryWrapper.lambda().eq(SupplierOrg::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(supplierOrgPageParam.getSortField(), supplierOrgPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierOrgPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierOrgPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierOrgPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierOrg::getSortCode);
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(SupplierOrg::getId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<Tree<String>> tree() {
        // 获取本单位所有机构
        List<SupplierOrg> allOrgList = this.list(new LambdaQueryWrapper<SupplierOrg>().eq(SupplierOrg::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        // 定义机构集合
        Set<SupplierOrg> supplierOrgSet = CollectionUtil.newHashSet();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            loginUserDataScope.forEach(orgId -> supplierOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
        } else {
            return CollectionUtil.newArrayList();
        }
        List<TreeNode<String>> treeNodeList = supplierOrgSet.stream().map(supplierOrg ->
                new TreeNode<>(supplierOrg.getId(), supplierOrg.getParentId(),
                        supplierOrg.getName(), supplierOrg.getSortCode()).setExtra(JSONUtil.parseObj(supplierOrg)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierOrgAddParam supplierOrgAddParam) {
        SupplierOrgCategoryEnum.validate(supplierOrgAddParam.getCategory());
        //如果不是超管，校验数据范围，只能修改下级机构名称
        if(ObjectUtil.notEqual(StpLoginUserUtil.getLoginUser().getAccount(), SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue())) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if (!loginUserDataScope.contains(supplierOrgAddParam.getParentId())) {
                    throw new CommonException("您没有权限在该机构下增加机构，机构id：{}", supplierOrgAddParam.getParentId());
                }
            } else {
                throw new CommonException("您没有权限增加机构");
            }
        }
        SupplierOrg supplierOrg = BeanUtil.toBean(supplierOrgAddParam, SupplierOrg.class);
        // 重复名称
        boolean repeatName = this.count(new LambdaQueryWrapper<SupplierOrg>().eq(SupplierOrg::getParentId, supplierOrg.getParentId())
                .eq(SupplierOrg::getName, supplierOrg.getName())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", supplierOrg.getName());
        }
        //数据归属
        supplierOrg.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        supplierOrg.setCode(RandomUtil.randomString(10));
        this.save(supplierOrg);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(SupplierDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(supplierOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierOrgEditParam supplierOrgEditParam) {
        SupplierOrgCategoryEnum.validate(supplierOrgEditParam.getCategory());
        SupplierOrg supplierOrg = this.queryEntity(supplierOrgEditParam.getId());
        //如果不是超管，校验数据范围，只能修改下级机构名称
        if(ObjectUtil.notEqual(StpLoginUserUtil.getLoginUser().getAccount(), SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue())){
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.contains(supplierOrg.getId())) {
                    throw new CommonException("您没有权限编辑该机构，机构id：{}", supplierOrg.getId());
                }
                if(!loginUserDataScope.contains(supplierOrg.getParentId())) {
                    throw new CommonException("您没有权限编辑该机构下的机构，机构id：{}", supplierOrg.getParentId());
                }
            } else {
                throw new CommonException("您没有权限编辑该机构，机构id：{}", supplierOrg.getId());
            }
        }
        BeanUtil.copyProperties(supplierOrgEditParam, supplierOrg);
        boolean repeatName = this.count(new LambdaQueryWrapper<SupplierOrg>().eq(SupplierOrg::getParentId, supplierOrg.getParentId())
            .eq(SupplierOrg::getName, supplierOrg.getName()).ne(SupplierOrg::getId, supplierOrg.getId())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", supplierOrg.getName());
        }
        List<SupplierOrg> originDataList = this.list();
        boolean errorLevel = this.getChildListById(originDataList, supplierOrg.getId(), true).stream()
            .map(SupplierOrg::getId).collect(Collectors.toList()).contains(supplierOrg.getParentId());
        if(errorLevel) {
            throw new CommonException("不可选择上级机构：{}", this.getById(originDataList, supplierOrg.getParentId()).getName());
        }
        this.updateById(supplierOrg);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(SupplierDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(supplierOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierOrgIdParam> supplierOrgIdParamList) {
        List<String> orgIdList = CollStreamUtil.toList(supplierOrgIdParamList, SupplierOrgIdParam::getId);
        if(ObjectUtil.isNotEmpty(orgIdList)) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(orgIdList)) {
                    throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
                }
            } else {
                throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
            }
            List<SupplierOrg> allOrgList = this.list();
            // 获取所有子机构
            List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
            orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
                    .map(SupplierOrg::getId).collect(Collectors.toList())));
            // 机构下有人不能删除（直属机构）
            boolean hasOrgUser = supplierUserService.count(new LambdaQueryWrapper<SupplierUser>().in(SupplierUser::getOrgId, toDeleteOrgIdList)) > 0;
            if(hasOrgUser) {
                throw new CommonException("请先删除机构下的人员");
            }
            // 机构下有人不能删除（兼任机构）
            List<String> positionJsonList = supplierUserService.list(new LambdaQueryWrapper<SupplierUser>()
                    .isNotNull(SupplierUser::getPositionJson)).stream().map(SupplierUser::getPositionJson).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(positionJsonList)) {
                List<String> positionOrgIdList = CollectionUtil.newArrayList();
                positionJsonList.forEach(positionJson -> JSONUtil.toList(JSONUtil.parseArray(positionJson), JSONObject.class)
                        .forEach(jsonObject -> positionOrgIdList.add(jsonObject.getStr("orgId"))));
                boolean hasPositionUser = CollectionUtil.intersectionDistinct(toDeleteOrgIdList, CollectionUtil.removeNull(positionOrgIdList)).size() > 0;
                if(hasPositionUser) {
                    throw new CommonException("请先删除机构下的人员");
                }
            }
            // 机构下有角色不能删除
            boolean hasRole = sysRoleApi.orgHasRole(toDeleteOrgIdList);
            if(hasRole) {
                throw new CommonException("请先删除机构下的角色");
            }
            // 机构下有岗位不能删除
            boolean hasPosition = supplierPositionService.count(new LambdaQueryWrapper<SupplierPosition>().in(SupplierPosition::getOrgId, toDeleteOrgIdList)) > 0;
            if(hasPosition) {
                throw new CommonException("请先删除机构下的岗位");
            }
            // 执行删除
            this.removeByIds(toDeleteOrgIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(SupplierDataTypeEnum.ORG.getValue(), toDeleteOrgIdList);
        }
    }

    @Override
    public SupplierOrg detail(SupplierOrgIdParam supplierOrgIdParam) {
        return this.queryEntity(supplierOrgIdParam.getId());
    }

    @Override
    public SupplierOrg queryEntity(String id) {
        SupplierOrg supplierOrg = this.getById(id);
        if(ObjectUtil.isEmpty(supplierOrg)) {
            throw new CommonException("机构不存在，id值为：{}", id);
        }
        return supplierOrg;
    }

    @Override
    public List<SupplierOrg> getAllOrgList(String companyId) {
        return this.list(new LambdaQueryWrapper<SupplierOrg>().eq(SupplierOrg::getCompanyId,companyId).orderByAsc(SupplierOrg::getSortCode));
    }

    @Override
    public String getOrgIdByOrgFullNameWithCreate(String orgFullName) {
        List<SupplierOrg> cachedAllOrgList = this.getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId());
        List<Tree<String>> treeList = TreeUtil.build(cachedAllOrgList.stream().map(supplierOrg ->
                new TreeNode<>(supplierOrg.getId(), supplierOrg.getParentId(), supplierOrg.getName(), supplierOrg.getSortCode()))
                .collect(Collectors.toList()), "0");
        return findOrgIdByOrgName("0", StrUtil.split(orgFullName, StrUtil.DASHED).iterator(), cachedAllOrgList, treeList);
    }

    public String findOrgIdByOrgName(String parentId, Iterator<String> iterator, List<SupplierOrg> cachedAllOrgList, List<Tree<String>> treeList) {
        String orgName = iterator.next();
        if(ObjectUtil.isNotEmpty(treeList)) {
            List<Tree<String>> findList = treeList.stream().filter(tree -> tree.getName().equals(orgName)).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(findList)) {
                if(iterator.hasNext()) {
                    return findOrgIdByOrgName(findList.get(0).getId(), iterator, cachedAllOrgList, findList.get(0).getChildren());
                } else {
                    return findList.get(0).getId();
                }
            }
        }
        String orgId = this.doCreateOrg(parentId, orgName, cachedAllOrgList);
        if(iterator.hasNext()) {
            return findOrgIdByOrgName(orgId, iterator, cachedAllOrgList, CollectionUtil.newArrayList());
        } else {
            return orgId;
        }
    }

    /**
     * 执行创建机构
     *
     * @author xuyuxiang
     * @date 2023/3/8 9:38
     **/
    public String doCreateOrg(String parentId, String orgName, List<SupplierOrg> cachedAllOrgList) {
        //创建该机构
        SupplierOrg supplierOrg = new SupplierOrg();
        supplierOrg.setName(orgName);
        supplierOrg.setCode(RandomUtil.randomString(10));
        supplierOrg.setParentId(parentId);
        supplierOrg.setCategory("0".equals(parentId)?SupplierOrgCategoryEnum.COMPANY.getValue():SupplierOrgCategoryEnum.DEPT.getValue());
        supplierOrg.setSortCode(99);
        this.save(supplierOrg);
        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(SupplierDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(supplierOrg));
        // 将该机构加入缓存
        cachedAllOrgList.add(supplierOrg);
        // 更新缓存
        commonCacheOperator.put(ORG_CACHE_ALL_KEY, cachedAllOrgList);
        return supplierOrg.getId();
    }

    /* ====机构部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<SupplierOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //Mr.wu 2024-9-20改为显示本单位全部机构
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        // 定义机构集合
        Set<SupplierOrg> supplierOrgSet = CollectionUtil.newHashSet();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<SupplierOrg> allOrgList = this.list();
            loginUserDataScope.forEach(orgId -> supplierOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = supplierOrgSet.stream().map(SupplierOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SupplierOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(SupplierOrg::getSortCode);
        List<SupplierOrg> supplierOrgList = this.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = supplierOrgList.stream().map(supplierOrg ->
                        new TreeNode<>(supplierOrg.getId(), supplierOrg.getParentId(), supplierOrg.getName(), supplierOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public List<SupplierOrg> orgListSelector(SupplierOrgSelectorOrgListParam supplierOrgSelectorOrgListParam) {
        LambdaQueryWrapper<SupplierOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //Mr.wu 2024-9-20改为显示本单位全部机构
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        // 定义机构集合
        Set<SupplierOrg> supplierOrgSet = CollectionUtil.newHashSet();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<SupplierOrg> allOrgList = this.list();
            loginUserDataScope.forEach(orgId -> supplierOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = supplierOrgSet.stream().map(SupplierOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SupplierOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(SupplierOrg::getSortCode);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public Page<SupplierUser> userSelector(SupplierOrgSelectorUserParam supplierOrgSelectorUserParam) {
        LambdaQueryWrapper<SupplierUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(SupplierUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(SupplierUser::getId, SupplierUser::getAvatar, SupplierUser::getOrgId, SupplierUser::getPositionId, SupplierUser::getAccount,
                SupplierUser::getName, SupplierUser::getSortCode, SupplierUser::getGender, SupplierUser::getEntryDate);

        if (ObjectUtil.isNotEmpty(supplierOrgSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(this.getChildListById(this
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), supplierOrgSelectorUserParam.getOrgId(), true), SupplierOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(SupplierUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        //排除超管
        lambdaQueryWrapper.ne(SupplierUser::getAccount, SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());

        if(ObjectUtil.isNotEmpty(supplierOrgSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(SupplierUser::getName, supplierOrgSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(SupplierUser::getSortCode);
        return supplierUserService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    /* ====以下为各种递归方法==== */

    @Override
    public List<SupplierOrg> getParentAndChildListById(List<SupplierOrg> originDataList, String id, boolean includeSelf) {
        List<SupplierOrg> parentListById = this.getParentListById(originDataList, id, false);
        List<SupplierOrg> childListById = this.getChildListById(originDataList, id, true);
        parentListById.addAll(childListById);
        return parentListById;
    }

    public List<SupplierOrg> getChildListById(List<SupplierOrg> originDataList, String id, boolean includeSelf) {
        List<SupplierOrg> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(originDataList, id, resultList);
        if(includeSelf) {
            SupplierOrg self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    @Override
    public List<SupplierOrg> getParentListById(List<SupplierOrg> originDataList, String id, boolean includeSelf) {
        List<SupplierOrg> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(originDataList, id, resultList);
        if(includeSelf) {
            SupplierOrg self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }


    public void execRecursionFindChild(List<SupplierOrg> originDataList, String id, List<SupplierOrg> resultList) {
        originDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(originDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<SupplierOrg> originDataList, String id, List<SupplierOrg> resultList) {
        originDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                SupplierOrg parent = this.getById(originDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(originDataList, item.getParentId(), resultList);
            }
        });
    }

    @Override
    public SupplierOrg getById(List<SupplierOrg> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, SupplierOrg::getId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }

    @Override
    public SupplierOrg getParentById(List<SupplierOrg> originDataList, String id) {
        SupplierOrg self = this.getById(originDataList, id);
        return ObjectUtil.isNotEmpty(self)?self:this.getById(originDataList, self.getParentId());
    }

    @Override
    public SupplierOrg getChildById(List<SupplierOrg> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, SupplierOrg::getParentId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }
}
